const { MongoClient } = require("mongodb");

const client = new MongoClient("mongodb://127.0.0.1:27017", {
  useUnifiedTopology: true,
});

async function createDocument() {
  console.log("-----------------------------");
  const testDb = client.db("test"); // 找数据库
  const pizzaCollection = testDb.collection("pizzaCollections");

  const pizzaDocument = {
    name: "Neapolitan pizza",
    shape: "round",
    toppings: ["San Marzano tomatoes", "mozzarella di bufala cheese"],
  };
  const pizzaDocuments = [
    { name: "Sicilian pizza", shape: "square" },
    { name: "New York pizza", shape: "round" },
    { name: "Grandma pizza", shape: "square" },
  ];

  const ret1 = await pizzaCollection.insertOne(pizzaDocument);
  console.log(ret1);
  const ret2 = await pizzaCollection.insertMany(pizzaDocuments);
  console.log(ret2);
}

async function run() {
  try {
    // start connection
    await client.connect();
    // 创建文档
    // createDocument();
    const testDb = client.db("test"); // 找数据库
    const pizzaCollection = testDb.collection("pizzaCollections");

    // const pizzaDocument = {
    //   name: "Neapolitan pizza",
    //   shape: "round",
    //   toppings: ["San Marzano tomatoes", "mozzarella di bufala cheese"],
    // };
    // const pizzaDocuments = [
    //   { name: "Sicilian pizza", shape: "square" },
    //   { name: "New York pizza", shape: "round" },
    //   { name: "Grandma pizza", shape: "square" },
    // ];

    // const ret1 = await pizzaCollection.insertOne(pizzaDocument);
    // console.log(ret1);
    // const ret2 = await pizzaCollection.insertMany(pizzaDocuments);
    // console.log(ret2);
    console.log("-------------------??");

    // 查询文档
    const ret = await pizzaCollection.find();
    console.log(await ret.toArray());
  } catch (error) {
    // connect error
    console.log("connect error", error);
  } finally {
    await client.close();
  }
}

run();
// // start connection
// client.connect().then(()=> {
//   // connect success

// }).catch(() => {
//   console.log("connect error");
// })
